2023/12/231499字符

图的搜索

function Node(value) {
    this.value = value;
    this.neighbor = [];
}

var a = new Node('a');
var b = new Node('b');
var c = new Node('c');
var d = new Node('d');
var e = new Node('e');

a.neighbor.push(b);
a.neighbor.push(c);
b.neighbor.push(a);
b.neighbor.push(c);
b.neighbor.push(d);
c.neighbor.push(a);
c.neighbor.push(b);
c.neighbor.push(d);
d.neighbor.push(b);
d.neighbor.push(c);
d.neighbor.push(e);
e.neighbor.push(d);

深度优先搜索

function deepFirstSearch(node, target, path = []) {
    if (node === null) return false;
    if (path.indexOf(node) > -1) return false;
    if (node.value === target) return true;
    path.push(node);
    var result = false;
    for (let i = 0; i < node.neighbor.length; i++) {
        result |= deepFirstSearch(node.neighbor[i], target, path);
    }
    return result ? true : false;
}

deepFirstSearch(b, 'c');  //--> true

广度优先搜索

function breadthFirstSearch(nodes, target, path = []) {
    if (nodes === null || nodes.length === 0) return false;
    let nextNodes = [];
    for (let i = 0; i < nodes.length; i++) {
        if (path.indexOf(nodes[i]) > -1) continue;
        path.push(nodes[i]);
        if (nodes[i].value === target) return true;
        else nextNodes = nextNodes.concat(nodes[i],neighor);
    }
    return breadthFirstSearch(nextNodes, target, path);
}

breadthFirstSearch([c], 'b');  //--> true